package com.cbarmstrong.MarketWatcher;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;

public class StateInformation implements Serializable{

	private static final long serialVersionUID = 1L;
	private HashMap<Integer,String> filePointers=new HashMap<Integer,String>();
	@SuppressWarnings("rawtypes")
	private HashMap bestSet = new HashMap<String, IndicatorProcessor>();
	
	public static StateInformation getInstance(){
		File f=new File(System.getProperty("stateFile", "/opt/FinanceTools/config/state"));
		if(System.getProperties().containsKey("debug")){ System.out.println("Loaded State info"); }
		if(f.exists()){ return StateInformation.load(f.getAbsolutePath()); }
		else{ return new StateInformation(); }
	}
	
	public void setFileReference(Integer i, String pair){ filePointers.put(i, pair); }
	
	public String getFileReference(Integer i){ 
		if(!filePointers.containsKey(i)){ filePointers.put(i,""); }
		return filePointers.get(i);
	}
	
	@SuppressWarnings("rawtypes")
	public void setBestSet(HashMap set){ bestSet=set; }
	
	@SuppressWarnings("rawtypes")
	public HashMap getBestSet(){ 
		if(bestSet==null){ return new HashMap(); }
		return bestSet; 
	}

	public boolean save(){
		String filename=System.getProperty("stateFile", "/opt/FinanceTools/config/state");
		if(System.getProperties().containsKey("debug")){ System.out.println("Saving state to "+filename); }
		FileOutputStream fos = null;
		ObjectOutputStream os = null;
		new File(new File(filename).getParent()).mkdirs();
		try {
			fos = new FileOutputStream(filename);
			os = new ObjectOutputStream(fos);
			os.writeObject(this);
			os.close();
			return true;
		} catch (IOException ex) {
			ex.printStackTrace();
			return false;
		}
	}

	@SuppressWarnings("resource")
	public static StateInformation load(String filename){
		FileInputStream fis = null;
		ObjectInputStream is = null;
		try {
			fis = new FileInputStream(filename);
			is = new ObjectInputStream(fis);
			return (StateInformation) is.readObject();
		} catch (IOException ex) {
			System.out.println("Failed to load state data: "+ex.getMessage());
			return null;
		} catch (ClassNotFoundException e) {
			System.out.println("Failed to load state data: "+e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

}
